//
//  DetailImageViewController.m
//  帮惠管理员
//
//  Created by reew on 2017/10/19.
//  Copyright © 2017年 reew. All rights reserved.
//

#import "DetailImageViewController.h"
#import <QBImagePickerController/QBImagePickerController.h>
#import "Admin.h"
#import "System.h"
#import "CommonUtils.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ImageCollectionViewCell.h"
@interface DetailImageViewController ()<QBImagePickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) QBImagePickerController *imagePicker;
@property (weak, nonatomic) IBOutlet UICollectionView *colllectionView;
//图片展示
@property (nonatomic,strong) NSMutableArray *imageArr;
@property (nonatomic,strong) NSMutableArray *imageNameArr;
@end

@implementation DetailImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initPickerView];
    [self setupNav];
    [self setUpCollectionView];
//    _imageNameArr =[NSMutableArray arrayWithArray:@[@"1.png",@"2.png",@"3.png",@"4.png",@"5.png"]] ;
}
- (void)setUpCollectionView{
    _colllectionView.delegate = self;
    _colllectionView.dataSource = self;
    [_colllectionView registerNib:[UINib nibWithNibName:@"ImageCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ImageCollectionViewCell"];
}
- (void)initPickerView{
    _imagePicker = [QBImagePickerController new];
    _imagePicker.delegate = self;
    _imagePicker.allowsMultipleSelection = YES;
        _imagePicker.maximumNumberOfSelection = 50;
    _imagePicker.prompt = @"选择图片";
}
- (void)setupNav{
    UIBarButtonItem *rightItem= [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save)];
    //    rightItem.tintColor = [UIColor blackColor];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.title = @"上传商品详情图";
}

    
- (void)openAlbulm{
    [self presentViewController:_imagePicker animated:YES completion:nil];
}
- (void)initImageNameArr{
    for (int i = 0; i<_imageArr.count; i++) {
        NSString *name = [NSString stringWithFormat:@"%d.png",i];
        [_imageNameArr addObject:name];
    }
}
- (void)save{
    {
//        [self initImageNameArr];
        [CommonUtils showHudWithStatus:LoadingStatus stayTime:1 info:nil];
        NSString *url = [kBaseURL stringByAppendingPathComponent:kadd_goods_detail_img];
        [CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            for (int i = 0; i<_imageArr.count; i++) {
                [formData appendPartWithFileData:UIImageJPEGRepresentation(_imageArr[i], 1) name:@"file" fileName:_imageNameArr[i] mimeType:@"image/png"];
            }
            
            [formData appendPartWithFormData:[_goodsNo dataUsingEncoding:NSUTF8StringEncoding] name:@"goodsNo"];
        } progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"%@",responseObject);
            [CommonUtils showHudWithStatus:NomormalStatus stayTime:1 info:responseObject[@"message"]];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"%@",error);
            [CommonUtils showHudWithStatus:ErrorStatus stayTime:1 info:error.domain];
        }];
    }
    
}
- (void)addNewImg{
    [self presentViewController:_imagePicker animated:YES completion:nil];
}
- (void)deletePhoto:(UIButton *)sender{
    
    [_imageArr removeObjectAtIndex:sender.tag];
    [_imagePicker.selectedAssets removeObjectAtIndex:sender.tag];
    
    [self.colllectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:sender.tag inSection:0]]];
    
    for (NSInteger item = sender.tag; item <= _imageArr.count; item++) {
        ImageCollectionViewCell *cell = (ImageCollectionViewCell*)[self.colllectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
        cell.closeButton.tag--;
        cell.profilePhoto.tag--;
        
        
    }
    
}
#pragma mark - QBImagePickerController
-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets{
    _imageArr = [NSMutableArray array];
    _imageNameArr = [NSMutableArray array];
    for (PHAsset *set in assets) {
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        options.version = PHImageRequestOptionsVersionUnadjusted;
        options.resizeMode = PHImageRequestOptionsResizeModeNone;
        [[PHImageManager defaultManager] requestImageForAsset:set targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
            //设置图片
            [self.imageArr addObject:result];
            NSString *imageName = [set valueForKey:@"filename"];
            NSString *temStr = [imageName stringByReplacingOccurrencesOfString:@"IMG_" withString:@""];
            NSLog(@"imageName:%@",temStr);
            [_imageNameArr addObject:temStr];
            [_colllectionView reloadData];
        }];
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
-(void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
#pragma mark - UICollectionViewDatasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imageArr.count+1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCollectionViewCell" forIndexPath:indexPath];
    cell.bottomMargin.constant = 0;
    cell.defaultBtn.hidden = YES;
    if (indexPath.row == _imageArr.count) {
        cell.profilePhoto.image = [UIImage imageNamed:@"ic_addphotos"];
        cell.closeButton.hidden = YES;
    }else{
        [cell.profilePhoto setImage:_imageArr[indexPath.item]];
        cell.closeButton.hidden = NO;
    }
    
    cell.profilePhoto.tag = [indexPath item];
    //添加图片cell点击事件
    cell.closeButton.tag = [indexPath item];
    [cell.closeButton addTarget:self action:@selector(deletePhoto:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
#pragma mark <UICollectionViewDelegate>
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == _imageArr.count) {
        [self openAlbulm];
    }
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(([UIScreen mainScreen].bounds.size.width-64) /4 ,([UIScreen mainScreen].bounds.size.width-64)/4-8);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 8, 10, 8);//
//    UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
